<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input v-model="spu.spuName" placeholder="SPU名称"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌">
          <el-option
            v-for="tm in trademarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="spu.description"
          type="textarea"
          rows="4"
          placeholder="描述"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!-- file-list是照片墙需要展示的数据[是个数组,且里面的元素必须有name和url属性] -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="attrIdAndAttrName"
          :placeholder="`还有${unSelectSaleAttr.length}个未选择`"
        >
          <el-option
            v-for="unselect in unSelectSaleAttr"
            :key="unselect.id"
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
          ></el-option>
        </el-select>
        <el-button
          style="margin-left: 8px"
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
        >
          添加销售属性
        </el-button>
        <el-table border style="width: 100%" :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column>
          <el-table-column label="属性值名称列表" width="width">
            <template #default="{ row }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.inputVisible"
                ref="saveTagInput"
                v-model="row.inputValue"
                class="input-new-tag"
                size="small"
                @blur="handleInputConfirm(row)"
                @keyup.enter.native="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
              >
                添加
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width">
            <template #default="{ $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getSpuInfoApi, getTrademarkListApi, getBaseSaleAttrListApi, getSpuImageListApi, addOrUpdateSpuApi } from '@/api/spu'

export default {
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      spu: {
        category3Id: 0,
        tmId: '',
        description: '',
        spuName: '',
        spuImageList: [
          // {
          //   'id': 0,
          //   'imgName': 'string',
          //   'imgUrl': 'string',
          //   'spuId': 0
          // }
        ],
        spuSaleAttrList: [
          // {
          //   'baseSaleAttrId': 0,
          //   'id': 0,
          //   'saleAttrName': 'string',
          //   'spuId': 0,
          //   'spuSaleAttrValueList': [
          //     {
          //       'baseSaleAttrId': 0,
          //       'id': 0,
          //       'isChecked': 'string',
          //       'saleAttrName': 'string',
          //       'saleAttrValueName': 'string',
          //       'spuId': 0
          //     }
          //   ]
          // }
        ]
      },
      trademarkList: [],
      spuImageList: [],
      baseSaleAttrList: [],
      // 未选择的销售属性的Id
      attrIdAndAttrName: ''
    }
  },
  computed: {
    // 计算还未选择的销售属性
    unSelectSaleAttr () {
      return this.baseSaleAttrList.filter(item => {
        return this.spu.spuSaleAttrList.every(item1 => {
          return item.name !== item1.saleAttrName
        })
      })
    }
  },
  methods: {
    // 取消按钮的回调
    cancel () {
      this.$emit('changeScene', 0)
      // 清空数据
      // ES6中新增的方法,用于合并对象
      // this._data可以操作data当中的响应式数据
      // this.$options可以获取配置对象,配置对象的data函数执行后返回的是空的响应式数据
      Object.assign(this._data, this.$options.data())
    },
    // 点击添加spu按钮的回调,发送请求
    async addSpuData (category3Id) {
      // 添加spu的时候收集三级分类的Id
      this.spu.category3Id = category3Id
      try {
        // 获取品牌信息
        const trademarkList = await getTrademarkListApi()
        this.trademarkList = trademarkList.data
        // 获取平台全部的销售属性
        const baseSaleAttrList = await getBaseSaleAttrListApi()
        this.baseSaleAttrList = baseSaleAttrList.data
      } catch (error) {
        console.log(error)
      }
    },
    // 保存按钮的回调
    async addOrUpdateSpu () {
      // 整理参数，整理照片墙数据
      // 对于图片数据需要携带imageName和imageUrl
      this.spu.spuImageList = this.spuImageList.map(item => {
        return {
          imageName: item.name,
          imageUrl: (item.response && item.response.data) || item.url
        }
      })
      // 发送请求
      try {
        const data = await addOrUpdateSpuApi(this.spu)
        console.log(data)
        this.$message.success('修改成功')
        this.$emit('changeScene', 0)
        // 清除数据 -> 先点击修改,再点击添加spu,也会有数据回显,所以要清除数据
        Object.assign(this._data, this.$options.data())
      } catch (error) {
        console.log(error)
      }
    },
    handleRemove (file, fileList) {
      // console.log(file, fileList)
      this.spuImageList = fileList
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess (response, file, fileList) {
      console.log(response, file, fileList)
    },
    async initSpuData (spu) {
      // console.log(spu, '发送请求')
      try {
        // 获取spu数据
        const { data } = await getSpuInfoApi(spu.id)
        // console.log(data)
        this.spu = data
        // 获取品牌信息
        const trademarkList = await getTrademarkListApi()
        this.trademarkList = trademarkList.data
        // 获取spu图片数据
        const spuImageList = await getSpuImageListApi(spu.id)
        // 由于照片墙显示图片时,需要name和url字段
        const listArr = spuImageList.data
        listArr.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        // this.spuImageList = spuImageList.data
        this.spuImageList = listArr
        // 获取平台全部的销售属性
        const baseSaleAttrList = await getBaseSaleAttrListApi()
        this.baseSaleAttrList = baseSaleAttrList.data
      } catch (error) {
        console.log(error)
      }
    },
    // 添加销售属性
    addSaleAttr () {
      // 把收集到的销售属性数据进行分割
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      // 向SPU对象的spuSaleAttrList数组添加新的销售属性
      const newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrList: [] }
      // 添加新的销售属性
      this.spu.spuSaleAttrList.push(newSaleAttr)
      // 清空数据
      this.attrIdAndAttrName = ''
    },
    // 添加按钮的回调
    addSaleAttrValue (row) {
      // 点击销售属性值的添加按钮时,button变为input,通过当前销售属性的inputVisible控制
      console.log(row)
      this.$set(row, 'inputVisible', true) // 挂载在销售属性身上的响应式数据inputVisible,控制button和input切换
      this.$set(row, 'inputValue', '') // 通过响应式数据inputValue字段收集新增的销售属性值
    },
    // el-input失去焦点的事件
    handleInputConfirm (row) {
      const { baseSaleAttrId, inputValue } = row
      if (inputValue.trim() === '') {
        return this.$message.error('属性值不能为空')
      }
      if (!row.spuSaleAttrValueList.every(item => item.saleAttrValueName !== inputValue)) {
        return this.$message.error('不能重复')
      }
      // 新增的销售属性值
      const newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
      row.spuSaleAttrValueList.push(newSaleAttrValue)
      row.inputVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
